package com.koron.order.linepatrol.satellite.controller;


import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.EasyExcelUtils;
import com.koron.order.linepatrol.satellite.bean.convertor.LinePatrolMonitorChangeConvertor;
import com.koron.order.linepatrol.satellite.bean.dto.LinePatrolMonitorChangeDTO;
import com.koron.order.linepatrol.satellite.bean.excel.LinePatrolMonitorChangeExcel;
import com.koron.order.linepatrol.satellite.bean.po.LinePatrolMonitorChange;
import com.koron.order.linepatrol.satellite.bean.query.LinePatrolMonitorChangeQuery;
import com.koron.order.linepatrol.satellite.excel.LinePatrolMonitorChangeExcelListener;
import com.koron.order.linepatrol.satellite.excel.LinePatrolSatelliteSSConverter;
import com.koron.order.linepatrol.satellite.service.LinePatrolMonitorChangeService;
import com.koron.order.linepatrol.satellite.service.LinePatrolSatelliteService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.perambulate.bean.excel.MonitorChangeExcel;
import com.koron.order.risk.base.excel.ErrorFillRowWriteHandler;
import com.koron.order.risk.feign.LineEquipmentFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * 卫星监测变化工单(LinePatrolMonitorChange)表控制层
 *
 * @author jzp
 * @since 2023-02-08 16:47:14
 */
@Slf4j
@Api(tags = "线路巡视-卫星监测变化工单接口")
@RestController
@RequestMapping("linePatrolMonitorChange")
public class LinePatrolMonitorChangeController {
    /**
     * 服务对象
     */
    @Autowired
    private LinePatrolMonitorChangeService linePatrolMonitorChangeService;

    @Autowired
    private LinePatrolSatelliteService linePatrolSatelliteService;

    @Autowired
    private LineEquipmentFeign equipmentFeign;

    @Autowired
    private LinePatrolMonitorChangeConvertor linePatrolMonitorChangeConvertor;

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping("getById")
    public Response<LinePatrolMonitorChange> selectOne(@RequestParam String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "getById", LinePatrolMonitorChange.class, id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询(详细记录)")
    @GetMapping("selectDetailById")
    public Response<LinePatrolMonitorChangeDTO> selectDetailById(String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "selectDetailById", LinePatrolMonitorChangeDTO.class, id));
    }
    @ApiOperation(value = "分页查询")
    @GetMapping("page")
    public Response<PageInfo<LinePatrolMonitorChange>> page(PageQuery pageQuery, LinePatrolMonitorChangeQuery query) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "page", PageInfo.class, pageQuery, query));
    }

    @ApiOperation(value = "保存")
    @PostMapping("save")
    public Response<LinePatrolMonitorChange> save(@RequestBody LinePatrolMonitorChange linePatrolMonitorChange) {
        ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "save", Boolean.class, linePatrolMonitorChange);
        return Response.ok(linePatrolMonitorChange);
    }

    @ApiOperation(value = "更新")
    @PutMapping("update")
    public Response<LinePatrolMonitorChange> update(@RequestBody LinePatrolMonitorChange linePatrolMonitorChange) {
        ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "update", Boolean.class, linePatrolMonitorChange);
        return Response.ok(linePatrolMonitorChange);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("delete")
    public Response delete(@RequestParam String id) {
        ADOConnection.runTask(getCurrDs(), linePatrolMonitorChangeService, "deleteById", Boolean.class, id);
        return Response.ok();
    }
    // 所有的线路设备数据
    @ApiOperation(value = "所有的线路,杆塔设备数据")
    @GetMapping("/allEquipment")
    public List<Equipment> allLineEquipment() {
        return ADOConnection.runTask(getCurrDs(), linePatrolSatelliteService, "allEquipments", List.class);
    }
    @SneakyThrows
    @ApiOperation(value = "模板")
    @GetMapping("/template")
    public void template2(HttpServletResponse response) {
        String path = "excel/import_monitor.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("卫星监视变化导入单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());

    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    public Response importFile(@RequestParam("file") MultipartFile file , @RequestParam("monitorId") String monitorId){
        LinePatrolSatelliteSSConverter stringConverter = new LinePatrolSatelliteSSConverter();
        LinePatrolMonitorChangeExcelListener monitorChangeListener = new LinePatrolMonitorChangeExcelListener(linePatrolMonitorChangeService, equipmentFeign, linePatrolMonitorChangeConvertor, monitorId);
        EasyExcel.read(file.getInputStream(), LinePatrolMonitorChangeExcel.class, monitorChangeListener)
                .registerConverter(stringConverter)
                .headRowNumber(1)
                .sheet(0)
                .doRead();
        if (monitorChangeListener.getExcelErrors().size() != 0) {
            String path = "excel/import_monitor_error.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(path);
            // 输出错误文件
            String filename = CodeTools.getCodeNo("MonitorFile", 3);
            String tempPath = EasyExcelUtils.createTempFile(filename, "xlsx");
            log.warn("导入失败，错误文件在：{}", tempPath);
            EasyExcel.write(tempPath)
                    .withTemplate(classPathResource.getInputStream())
                    .head(MonitorChangeExcel.class)
                    .needHead(false)
                    .registerConverter(stringConverter)
                    .registerWriteHandler(new ErrorFillRowWriteHandler(monitorChangeListener.getExcelErrors()))
                    .sheet(0)
                    .doWrite(monitorChangeListener.getErrorRisk());
            return Response.ok("temp/" + filename + ".xlsx");
        }
        return Response.ok("导入成功", null);
    }
}

